package cn.wolfcode.p2p.interceptor;

import cn.wolfcode.p2p.base.annotation.IsLoginAnno;
import cn.wolfcode.p2p.util.JSONResult;
import cn.wolfcode.p2p.util.UserContext;
import com.alibaba.fastjson.JSON;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@Component
public class LoginInterceptor extends HandlerInterceptorAdapter {
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
                //判断方法是不是方法,转成方法后判断有没有这个贴这个注解然后判断有没有登录
                if(handler instanceof HandlerMethod){
                        HandlerMethod method = (HandlerMethod) handler;
                        if(method.hasMethodAnnotation(IsLoginAnno.class)&& UserContext.getLoginInfo()==null){
                                if(method.hasMethodAnnotation(ResponseBody.class)){
                                        response.setCharacterEncoding("utf-8");
                                        response.setContentType("text/json,charset=utf-8");
                                        PrintWriter writer = response.getWriter();
                                        JSONResult jsonResult = new JSONResult();
                                        jsonResult.setMsg("请先登录!");
                                        writer.print(JSON.toJSONString(jsonResult));
                                        writer.close();
                                }else{

                                        response.sendRedirect("/login.html");
                                }

                                return false;
                        }
                }
                return true;
        }
}
